package payment

import (
	"cloud_android_backend/pkg/config"
	"fmt"
	"github.com/golang/glog"
	"github.com/smartwalle/alipay/v3"
)

type Alipay struct {
	Amount      float64
	Remark      string
	Description string
	OutTradeNo  string
	Subject     string
	Url         string
}

var AlipayClient *alipay.Client

func init() {
	config1 := config.GetConfig()
	fmt.Println("config1:", config1)
	appID := config1.Alipay.AppId
	privateKey := config1.Alipay.PrivateKey
	var err error
	fmt.Printf("appid:%s,privateKey:%s", appID, privateKey)
	AlipayClient, err = alipay.New(appID, privateKey, true)
	if err != nil {
		glog.Errorf("init alipay failed:err %v", err)
	}
	// 加载支付宝公钥证书（或普通公钥）
	if err = AlipayClient.LoadAliPayPublicKey(config1.Alipay.PublicKey); err != nil {
		glog.Errorf("load alipay public key failed:err %v", err)
	}

}
func (a *Alipay) Payment() (string, error) {
	var p = alipay.TradePagePay{}
	if a.Url != "" {
		p.ReturnURL = a.Url
	}

	config1 := config.GetConfig()
	p.NotifyURL = config1.Alipay.NotifyUrl // 异步通知地址
	//p.ReturnURL = config1.Alipay.ReturnUrl // 同步跳转地址
	p.Subject = a.Subject
	p.OutTradeNo = a.OutTradeNo
	p.TimeoutExpress = "5m"
	p.TotalAmount = fmt.Sprintf("%.2f", 0.01) // a.Amount
	p.ProductCode = "FAST_INSTANT_TRADE_PAY"

	url, err := AlipayClient.TradePagePay(p)
	a.Url = url.String()
	if err != nil {
		return url.String(), err
	}
	return url.String(), nil
}

func (wa *Alipay) GetResultType() ResultType {
	return ResultTypeUrl
}

func (a *Alipay) GetResult() string {
	return a.Url
}
